import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
let base = `${process.env.BASE_URL}` // 动态获取二级目录

import Login from "@/views/Login"

var router = new VueRouter({
	mode: 'history',
	base:base,
	routes: [
	{
		path:"/login",
		name:"Login",
		component:Login,
		meta:{
			title:"登录",
			icon:""
		}
	}

],
	scrollBehavior(to, from, savedPosition) {
	    if (savedPosition) {
	        return savedPosition
	    } else {
	        return {
	            x: 0,
	            y: 0
	        }
	    }
	}
});

import {setRouter} from "./permissions"
import {Message} from "element-ui"
import store from "@/store"
router.beforeEach((to,from,next)=>{
	let isLogin = store.state.user.userInfo;
	if(to.name != "Login" && !isLogin){
		return next({path:"/login",query:{redirect:to.name}})
	}else{
		if (router.options.routes.length == 1) {
			//登录成功后第一次进入 动态添加路由表
		    let newRoute = setRouter(to);
		    router.options.routes = newRoute.concat(router.options.routes)
		    router.options.routes.push({
		        path: '*',
		        redirect: router.options.routes[0].path,
		        meta: { title: '' },
		    })
		    router.addRoutes(router.options.routes)
		    if (router.options.routes[0].name == "Login") {
		        // Message.error('当前用户没有任何权限！');
		        localStorage.clear();
		        sessionStorage.clear();
		    }
			if(to.name == "Login"){
				let r = router.options.routes[0];
				let newToName = r.children?r.children[0].name:r.name;
				let newPath = r.children?r.path +"/" + r.children[0].path:r.path;
				return next({name:newToName,path:newPath})
			}
		}else{
			//正常
			console.log(to);
		}
	}

	return next()
})

export default router;
